package cmd

import (
	"bytes"
	"fmt"
	"gitee.com/lllgo/opsctl/pkg/model"
	"gitee.com/lllgo/opsctl/pkg/tools"
	"github.com/spf13/cobra"
	"strings"
)

// tag命令 用于查找已配置机器安装软件 说明：结果只是表示opsctl操作的结果，并不一定与服务器保持一致
// tag管理实现逻辑:
// 1. 安装软件命令查找hosts时添加tag
// 2. 卸载软件命令查找hosts时删除tag
func tagCmd() *cobra.Command {
	var host bool
	var software bool
	var all bool

	var tmp = &cobra.Command{
		Use:   "tag",
		Short: "查看服务器安装软件或安装软件的服务器",
		Run: func(cmd *cobra.Command, args []string) {
			sb := bytes.NewBufferString("")
			if len(args) == 0 {
				all = true
			}
			if all {
				sb.WriteString("ip\tname\ttags\n")
				for _, tag := range model.GetTags() {
					sb.WriteString(strings.Join([]string{tag.IP, tag.Name, tag.Tags}, "\t") + "\n")
				}
			} else if host {
				for _, tag := range model.GetTagsByHost(tools.GetHosts(args...)...) {
					sb.WriteString(tag.Tags + "\n")
				}
			} else if software {
				for _, tag := range model.GetTags(args...) {
					sb.WriteString(tag.Name + "\t" + tag.IP + "\n")
				}
			}

			fmt.Println(sb.String())
		},
	}
	tmp.Flags().BoolVarP(&host, "host", "", false, "打印指定host安装的软件")
	tmp.Flags().BoolVarP(&software, "software", "s", false, "打印已安装软件的服务器IP")
	tmp.Flags().BoolVarP(&all, "all", "a", true, "打印所有机器上安装的软件")
	return tmp
}
